/*
 * @Author: Crism
 * @Date: 2018-10-31 09:58:30
 * @LastEditors: Crism
 * @LastEditTime: 2018-11-21 15:30:04
 * @Email: crism@qq.com
 * @Description: 
 */

const db_cms = require('../config').db_cms;
const db_user = require('../config').db_user;

/** 获取评论列表 */
module.exports.get_comments_list = get_comments_list;
async function get_comments_list(item_id, begin, plen) {
    item_id = db_cms.escape(item_id);
    let sql = 'SELECT comment_id,commenter_id,commenter_img,commenter_name,comment_content,comment_time,like_num,by_review_id,by_reviewer_name,by_reviewer_id,by_reviewer_content FROM `comments` WHERE	item_id=' + item_id + ' ORDER BY comment_time DESC LIMIT ' + begin + ',' + plen;
    let comments_list = await db_cms.query(sql);
    if (comments_list instanceof Array && comments_list.length > 0) {
        return comments_list;
    }
    return [];
}
/** 获取热评论列表 */
module.exports.get_hot_comments_list = get_hot_comments_list;
async function get_hot_comments_list(item_id) {
    item_id = db_cms.escape(item_id);
    let sql = 'SELECT comment_id,commenter_id,commenter_img,commenter_name,comment_content,comment_time,like_num,by_review_id,by_reviewer_name,by_reviewer_id,by_reviewer_content FROM `comments` WHERE item_id = ' + item_id + ' ORDER BY like_num DESC LIMIT 4';
    let comments_list = await db_cms.query(sql);
    if (comments_list instanceof Array && comments_list.length > 0) {
        return comments_list;
    }
    return [];
}

/** 删除评论 */
module.exports.del_comments = del_comments;
async function del_comments(comment_id, commenter_id) {
    commenter_id = db_cms.escape(commenter_id);
    let sql = 'select item_id,item_type from comments where comment_id=' + comment_id + ' and commenter_id=' + commenter_id;
    let comment_info = await db_cms.queryOne(sql);
    if (comment_info == null) {
        return [false, '评论不存在!'];
    }
    let item_id = db_cms.escape(comment_info['item_id']);
    let item_type = comment_info['item_type'];
    let connection = await db_cms.getConnection();
    if (connection == null) {
        console.trace('trace connection fail');
        return [false, '服务连接异常!'];
    }
    let flag = true;
    try {
        await connection.beginTransaction();

        sql = 'delete from comments WHERE comment_id=' + comment_id;
        await connection.query(sql);
        /** 评论数减1 */
        if (item_type == 1) {
            sql = 'update music_info set comment_num=comment_num-1 where music_id=' + item_id;
            await connection.query(sql);
        } else if (item_type == 2) {
            sql = 'UPDATE `albums_info` SET comment_num=comment_num-1 where albums_id=' + item_id;
            await connection.query(sql);
        }
        
        await connection.commit();
    } catch (err) {
        /**
         * TODO
         * 日志系统
         */
        console.trace(err);
        await connection.rollback();
        flag = false;
    }
    if (connection) {
        db_cms.releaseConnection(connection);
    }
    return [flag, flag?'操作成功':'操作失败'];
}

/** 评论是否存在 */
module.exports.get_comments_like_num = get_comments_like_num;
async function get_comments_like_num(comment_id) {
    let sql = 'select like_num from comments WHERE comment_id=' + comment_id;
    let flag = await db_cms.queryOne(sql);
    if (flag != null) {
        return flag['like_num'];
    }
    return null;
}

/** 点赞/取消点赞 */
module.exports.update_like_num = update_like_num;
async function update_like_num(comment_id, num_flag) {
    let sql = 'UPDATE comments SET like_num=like_num +' + num_flag + ' WHERE comment_id=' + comment_id;
    let flag = await db_cms.queryNum(sql);
    return flag < 1 ? false : true;
}

/** 获取被回复信息 */
module.exports.get_by_reply_content = get_by_reply_content;
async function get_by_reply_content(commenter_id, comment_id) {
    commenter_id = db_cms.escape(commenter_id);
    let sql = 'SELECT commenter_id,commenter_name,comment_content,item_type FROM `comments` where comment_id=' + comment_id + ' and commenter_id=' + commenter_id;
    let reply = await db_cms.queryOne(sql);
    if (reply != null) {
        return [commenter_id, db_cms.escape(reply['commenter_name']), db_cms.escape(reply['comment_content']), reply['item_type']];
    }
    return [null, null, null, null];
}

/** 发表评论 */
module.exports.publish_comments = publish_comments;
async function publish_comments(commenter_id, item_id, comment_content, item_type, by_review_id, by_reviewer_content, by_reviewer_name, by_reviewer_id) {
    /** 获取用户信息 */
    commenter_id = db_user.escape(commenter_id);
    let sql = 'select user_name,image_id from ty_user where ty_id=' + commenter_id;
    let user_info = await db_user.queryOne(sql);
    if (user_info == null) {
        return [false, '用户信息错误!'];
    }
    /** 事物处理 */
    let connection = await db_cms.getConnection();
    if (connection == null) {
        console.trace('trace connection fail');
        return [false, '服务连接失败!'];
    }
    let flag = true;
    let item_object = -1;
    let comment_id = 0;
    try {
        await connection.beginTransaction();
        /** 首先判断评论对象是否存在 
         * 1: 音乐
         * 2: 专辑
         * 3: 歌单
        */
        item_id = db_cms.escape(item_id);
        if (item_type == 1) {
            /** 音乐评论次数加1 */
            sql = 'UPDATE music_info set comment_num=comment_num+1 where music_id=' + item_id;
            item_object = await connection.query(sql);
            let num = item_object['affectedRows'] || -1;
            if (num < 0) {
                throw new Error(500, "评论对象不存在!");
            }
        } else if (item_type == 2) {
            /** 专辑评论次数加1 */
            sql = 'UPDATE albums_info set comment_num=comment_num+1 where albums_id=' + item_id;
            item_object = await connection.query(sql);
            let num = item_object['affectedRows'] || -1;
            if (num < 0) {
                throw new Error(500, "评论对象不存在!");
            }
        }
        /** 发布评论 */
        let commenter_img = user_info['image_id'];
        let commenter_name = db_cms.escape(user_info['user_name']);
        comment_content = db_cms.escape(comment_content);
        sql = 'INSERT INTO comments(item_id,item_type,commenter_id,commenter_img,commenter_name,comment_content,comment_time,like_num,by_review_id,by_reviewer_content,by_reviewer_name,by_reviewer_id) VALUE(' + item_id + ',' + item_type + ',' + commenter_id + ',' + commenter_img + ',' + commenter_name + ',' + comment_content + ',UNIX_TIMESTAMP(NOW()),0,' + by_review_id + ',' + by_reviewer_content + ',' + by_reviewer_name + ',' + by_reviewer_id + ')';
        let res = await connection.query(sql)
        comment_id = res.insertId || -1;
        if (comment_id < 1) {
            throw new Error(500, "发表失败!");
        }
        /** 提交事物 */
        await connection.commit();
    } catch (err) {
        /**
         * TODO
         * 日志系统
         */
        console.trace(err);
        await connection.rollback();
        flag = false;
    }
    if (connection) {
        db_cms.releaseConnection(connection);
    }
    return [flag, flag ? comment_id : '发布失败!'];
}
